import { lk_buyer,lk_common,lk_expert,lk_seller,lk_manager,lk_consumer } from '@/config/myConfig.js';
import storage from "@/utils/storage.js"
// 对网络请求重新封装，等待登陆后请求，防止token失败
function request(method, url, data, header) {
	return new Promise((resolve, reject) => {
		if (getApp().globalData._IsLogin_) {
			// console.warn("直接登陆："+url);
			requestX(method, url, data, header).then(function(data) {
				resolve(data);
			}).catch(function(data) {
				reject(data);
			})
		} else {
			// 设置定时器，等待登陆完成
			let cnt = 0;
			let tid = setInterval(() => {
				if (cnt > 2000) { //设置最大等待时间
					clearInterval(tid);
					reject("请求超时，请刷新重试！");
					return;
				}
				// console.warn("等待登陆完成："+(++cnt));
				if (getApp().globalData._IsLogin_) {
					// console.warn("等待登陆成功："+cnt+" ---"+url);
					clearInterval(tid);
					requestX(method, url, data, header).then(function(data) {
						resolve(data);
					}).catch(function(data) {
						reject(data);
					})
				}
			}, 10)
		}
	})
}

function requestX(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
		'Authorization': uni.getStorageSync('token'),
		'Authorization_jbs': uni.getStorageSync('token')
	}, header)
	return new Promise((resolve, reject) => {
		// uni.showLoading();
		uni.request({
			url,
			method,
			data,
			header: headers,
			success: ({
				data: res
			}) => {
				//  uni.hideLoading() 
				if (res && res.code.code === 200) {
					try {
						const _data_ = JSON.parse(res.data || '{}');
						resolve(_data_);
					} catch (error) {
						resolve(res.data);
					}
				} else {
					uni.showToast({
						title: res.message || '服务器响应超时,请稍后再试！',
						icon: 'none'
					});
					reject(res.message);
				}
			},
			fail: function(res) {
				console.log(res, 9999)
				uni.hideLoading();
				uni.showToast({
					title: res.message || '网络响应超时,请稍后再试！',
					icon: 'none'
				});
				reject(res.data);
			}
		});
	})
}

function requesthttpLogin(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
	}, header)
	return new Promise((resolve, reject) => {
		uni.showLoading();
		uni.request({
			url,
			method,
			data,
			header: headers,
			success: ({
				data: res
			}) => {
				uni.hideLoading();
				resolve(res);
			},
			fail: function(res) {
				uni.hideLoading();
				uni.showToast({
					title: res.message || '网络响应超时,请稍后再试！',
					icon: 'none'
				});
				reject(res);
			}
		});
	})
}

function requesthttp(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
		'accessToken': storage.getAccessToken(),
		'refreshToken': storage.getRefreshToken(),
		// 'Authorization': uni.getStorageSync('token'),
		// 'Authorization_jbs': uni.getStorageSync('token'),
		// 'accessToken':null,
	}, header)
	return new Promise((resolve, reject) => {
		uni.hideLoading();
		uni.request({
			url,
			method,
			data,
			header: headers,
			success: ({
				data: res
			}) => {
				uni.hideLoading();
				resolve(res);
			},
			fail: function(res) {
				uni.hideLoading();
				uni.showToast({
					title: res.message || '网络响应超时,请稍后再试！',
					icon: 'none'
				});
				reject(res);
			}
		});
	})
}

function requestlist(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
		'Authorization':storage.getAccessToken(),
		'Authorization_jbs': storage.getAccessToken()
	}, header)
	return new Promise((resolve, reject) => {
		if (getApp().globalData._IsLogin_) {
			// console.warn("直接登陆："+url);
			requestlistX(method, url, data, header).then(function(data) {
				resolve(data);
			}).catch(function(data) {
				reject(data);
			})
		} else {
			// 设置定时器，等待登陆完成
			let cnt = 0;
			let tid = setInterval(() => {
				if (cnt > 500) { //设置最大等待时间
					clearInterval(tid);
					reject("请求超时，请刷新重试！");
					return;
				}
				// console.warn("等待登陆完成："+(++cnt));
				if (getApp().globalData._IsLogin_) {
					// console.warn("等待登陆成功："+cnt+" ---"+url);
					clearInterval(tid);
					requestlistX(method, url, data, header).then(function(data) {
						resolve(data);
					}).catch(function(data) {
						reject(data);
					})
				}
			}, 10)
		}
	})
}

function requestlistX(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
		'Authorization': storage.getAccessToken(),
		'Authorization_jbs': storage.getAccessToken()
	}, header)
	return new Promise((resolve, reject) => {
		// uni.hideLoading();
		uni.request({
			url,
			method,
			data,
			header: headers,
			success(res) {
				// uni.hideLoading();
				resolve(res.data);
			},
			fail: function(res) {
				// uni.hideLoading();
				uni.showToast({
					title: res.message || '网络响应超时,请稍后再试！',
					icon: 'none'
				});
				reject(res);
			}
		});
	})
}

function requestRight(method, url, data, header) {
	let headers = Object.assign({
		'content-type': 'application/json',
		'Authorization': storage.getAccessToken(),
		'Authorization_jbs': storage.getAccessToken(),
		'accessToken': storage.getAccessToken(),
	}, header)
	return new Promise((resolve, reject) => {
		// uni.hideLoading();
		uni.request({
			url: url,
			method,
			header: headers,
			success(res) {
				// uni.hideLoading();
				resolve(res.data);
			},
			fail: function(res) {
				// uni.hideLoading();
				uni.showToast({
					title: res.message || '网络响应超时,请稍后再试！',
					icon: 'none'
				});
				reject(res);
			}
		});
	})
}
export const userApi = {
	/**
	 * @param { code,mobile }
	 * @description 短信登录接口
	 * @detail 已联调
	 */
	smsLogin: (data) => requesthttpLogin('POST', `${lk_expert}/expert/passport/smsLogin`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
	/**
	 * @param { mobile,uuid,verificationEnums }
	 * @description 发送短信验证码,一分钟同一个ip请求1次
	 * @detail 已联调
	 */
	getCodeByPhone: (verificationEnums,mobile,data) => requesthttp('GET', `${lk_common}/common/common/sms/${verificationEnums}/${mobile}`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),

// 实名认证
/**
	  * @param { }
	  * @description 发起金融级实人认证请求
	  * @detail ？
	  */
	 initFaceVerify: (data) => requesthttp('POST', `${lk_common}/common/common/facebody/initFaceVerify`, data, {
	  'content-type': 'application/json'
	 }),
	 
	 /**
	  * @param { }
	  * @description 验证实人认证结果
	  * @detail ？
	  */
	 verifyResult: (data) => requesthttp('POST', `${lk_common}/common/common/facebody/describeFaceVerify`, data, {
	  'content-type': 'application/json'
	 }),
	/**
	  * @param {realName, idCard}
	  * @description 通知认证结果
	  */
	 postSendResult: (data) => requesthttp('POST', `${lk_buyer}/buyer/passport/member/realAuthentication`, data, {
	  'content-type': 'application/json'
	 }),

	/**
	 * @param {password,username}
	 * @description 专家登录接口
	 * @detail 已联调
	 */
	userLogin: (data) => requesthttpLogin('POST', `${lk_expert}/expert/passport/userLogin`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}), 
	/**
	 * @param { mobile, password, code }
	 * @description 通过短信重置密码
	 * @detail 已联调
	 */
	resetByMobile: (data) => requesthttpLogin('POST', `${lk_expert}/expert/passport/resetByMobile`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
	/**
	 * @param { }
	 * @description 获取当前登录用户接口-信息(登录后获取)
	 * @detail 已联调
	 */
	expertInfo: (data) => requesthttp('GET', `${lk_expert}/expert/passport`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
	
	/**
	 * @param { idCard,metaInfo,realName}
	 * @description 核身认证移动端请求1
	 * @detail 
	 */
	facebodyRequest: (data) => requesthttp('POST', `${lk_common}/common/common/facebody/request`, data, {
		'content-type': 'application/json'
	}),
	/**
	 * @param { action,materialHash,verificationToken}
	 * @description 核身认证移动端请求2
	 * @detail 
	 */
	facebodyQuery: (data) => requesthttp('POST', `${lk_common}/common/common/facebody/query`, data, {
		'content-type': 'application/json'
	}),
	/**
	 * @param {realName,idCard,credentials,domain,introduction...}
	 * @description 修改用户自己资料
	 * @detail 
	 */
	realAuthentication: (data) => requesthttp('POST', `${lk_expert}/expert/passport/realAuthentication`, data, {
		'content-type': 'application/json'
	}),
	/**
	 * @param {credentials,domain,introduction...}
	 * @description 修改用户自己资料
	 * @detail 
	 */
	editOwn: (data) => requesthttp('PUT', `${lk_expert}/expert/passport/editOwn`, data, {
		'content-type': 'application/json'
	}),
	
	/**
	 * @param { }
	 * @description 个人中心专家用户信息 
	 * @detail ？
	 */
	u_center: (data) => requesthttp('GET', `${lk_expert}/expert/passport/center`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
	
	
	/**
	 * @param { }
	 * @description 获取IM账号 
	 * @detail ？
	 */
	g_imaccount: (data) => requesthttp('GET', `${lk_expert}/order/userConsult/createIMAccount`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
	// 获取直播规则 
	getLiveRule: (data) => requesthttp('GET', `${lk_manager}/manager/other/article/type/LIVE_BROADCAST`, data, {
		'content-type': 'application/x-www-form-urlencoded'
	}),
		
}
